package cn.xd.security.userDetail;

import cn.xd.base.domain.bean.response.AdminUserForLoginDTO;
import cn.xd.common.enums.IBaseEnum;
import cn.xd.common.enums.common.CommonStatusEnum;
import cn.xd.security.userDetail.base.BaseUserDetails;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Set;


/**
 * 系统用户认证信息
 *
 * @author <a href="mailto:xianrui0365@163.com">haoxr</a>
 * @date 2021/9/27
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class AdminUserDetails extends BaseUserDetails {
    /**
     * 扩展字段：部门ID
     */
    private Long orgId;

    /**
     * 用户角色数据权限集合
     */
    private Integer dataScope;

    /**
     * 默认字段
     */
    private String account;


    private String pwd;

    private CommonStatusEnum status;
    private Set<String> perms;

    /**
     * 系统管理用户
     */
    public AdminUserDetails() {
    }


    public static AdminUserDetails newAdminUserDetails(AdminUserForLoginDTO user, Long orgId) {
        AdminUserDetails details = new AdminUserDetails();
        details.setId(user.getId());
        details.setOrgId(orgId);
        details.setName(user.getName());
        details.setAvatarUrl(user.getAvatarUrl());
        details.setGender(user.getGender());
        details.setAccount(user.getAccount());
        details.setPwd(user.getPwd());
        details.setDataScope(user.getDataScope());
        details.setStatus(IBaseEnum.getEnumByCode(user.getStatus(), CommonStatusEnum.class));
        details.setPerms(user.getPerms());
        return details;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Lists.newArrayList();
    }

    @Override
    public String getPassword() {
        return this.pwd;
    }

    @Override
    public String getUsername() {
        return this.account + "@" + this.getOrgId().toString();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !CommonStatusEnum.DISABLE.equals(status);
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return CommonStatusEnum.ENABLE.equals(status);
    }
}
